package com.kova.api.verify;

import java.util.Optional;
import java.util.function.Predicate;

/**
 * 参数校验器
 *  使用示例：
 *      ParamVerifier<String, String> verifier = new ParamVerifier<>();
 *      Optional<String> finish = verifier
 *         .verify("email@email.com", t -> isEmail(t), "email false")
 *         .verify("18888888888", t -> Pattern.matches("^1\\d{10}", t), "phone false")
 *         .finish();
 */
public class ParamVerifier<K, R> {

    private Optional<R> optional = Optional.empty();

    /**
     *
     * @param input predicate的入参
     * @param predicate 若前次为true, 且本次为predicate返回false, 保存本次失败的原因
     * @param result 失败的原因
     * @return this
     */
    public ParamVerifier<K, R> verify(K input, Predicate<K> predicate, R result)  {
        if(!optional.isPresent() && !predicate.test(input)) {
            optional = Optional.of(result);
        }
        return this;
    }

    public Optional<R> finish() {
        return optional;
    }

}
